import SearchPanel from './search-panel';
import React, { useEffect, useState } from 'react';
import { cleanObject, useMount, useDebounce } from '../../utils/index';
import qs from 'qs';
import List from './list';
const apiUrl = 'http://localhost:3001';

const ProjectListScreen = () => {
    const [param, setParam] = useState({
        name: '',
        personId: '',
    });
    const [list, setList] = useState([]);
    const [users, setUsers] = useState([]);
    const debouncedParam = useDebounce(param, 2000);

    useEffect(() => {
        fetch(
            `${apiUrl}/projects?${qs.stringify(cleanObject(debouncedParam))}`
        ).then(async (res) => {
            if (res.ok) {
                setList(await res.json());
            }
        });
    }, [debouncedParam]);

    useMount(() => {
        fetch(`${apiUrl}/users`).then(async (res) => {
            if (res.ok) {
                setUsers(await res.json());
            }
        });
    });
    return (
        <div>
            <SearchPanel param={param} setParam={setParam} users={users} />
            <List list={list} users={users} />
        </div>
    );
};

export default ProjectListScreen;
